//package com.qcu.service;
//
//import com.alibaba.fastjson2.JSON;
//import com.alibaba.fastjson2.JSONObject;
//import com.itextpdf.text.DocumentException;
//import com.qcu.email.ToEmail;
//import com.qcu.mapper.ExaminationInfoMapper;
//import com.qcu.util.PdfUtil;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Value;
//import org.springframework.data.redis.connection.stream.*;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.mail.javamail.JavaMailSender;
//import org.springframework.mail.javamail.MimeMessageHelper;
//import org.springframework.stereotype.Service;
//
//import javax.annotation.PostConstruct;
//import javax.annotation.Resource;
//import javax.mail.MessagingException;
//import javax.mail.internet.MimeMessage;
//import javax.mail.util.ByteArrayDataSource;
//import java.io.IOException;
//import java.time.Duration;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//import java.util.concurrent.ExecutorService;
//import java.util.concurrent.Executors;
//
///**
// * @Name: MyComputer
// * @ClassName EmailService
// * @Description:
// * @date 2025/2/11 16:16
// */
//@Service
//@Slf4j
//public class EmailService {
//
//    @Value("${spring.mail.username}")
//    private String from;
//
//    @Resource
//    JavaMailSender javaMailSender;
//
//    @Resource
//    private ExaminationInfoMapper examinationInfoMapper;
//
//    @Resource
//    RedisTemplate redisTemplate;
//
//    private static final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadExecutor();
//    private static final String QUEUE_NAME = "send.mail";
//    private static final String GROUP_NAME = "GROUP1";
//    private static final String CONSUMER_NAME = "NAME1";
//
//    // 初始化时执行
//    @PostConstruct
//    private void init() {
//        if (Boolean.FALSE.equals(redisTemplate.hasKey(QUEUE_NAME))){
//            redisTemplate.opsForStream().createGroup(QUEUE_NAME, ReadOffset.from("0"),GROUP_NAME);
//            log.info("创建队列");
//        }
//        EXECUTOR_SERVICE.submit(new Executor());
//    }
//
//    private class Executor implements Runnable{
//        @Override
//        public void run() {
//            while (true){
//                try{
//                    log.info("------------我开始执行啦");
//                    // 获取消息队列中的订单信息 XREADGROUP GROUP g1 c1 COUNT 1 BLOCK 2000 STREAMS stream.orders >
//                    List<MapRecord<String,Object,Object>> list = redisTemplate.opsForStream().read(
//                            Consumer.from(GROUP_NAME, CONSUMER_NAME),
//                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
//                            StreamOffset.create(QUEUE_NAME, ReadOffset.lastConsumed())
//                    );
//                    log.info("-----------第一步");
//
//                    // 如果获取失败，说明没有消息，继续下一次循环
//                    if (list == null || list.isEmpty()){
//                        continue;
//                    }
//                    log.info("-----------第二步");
//
//                    // 获取消息体
//                    MapRecord<String, Object, Object> record = list.get(0);
//                    Map<Object, Object> value = record.getValue();
//
//                    // 发送邮件消息
//                    log.info("------------获取到消息：{}",value.get("inhabitantId").toString());
//                    sendResultToUser(value.get("inhabitantId").toString());
//
//                    log.info("------------发送邮件成功");
//                    // ack消息确认
//                    redisTemplate.opsForStream().acknowledge(QUEUE_NAME,GROUP_NAME,record.getId());
//
//                }catch (Exception e){
//                    // todo: pending处理 ----> 已完成
//                    log.info("进入异常处理，开始处理pendingList");
//                    handlePendingList();
//                }
//            }
//        }
//
//        public void sendResultToUser(String inhabitantId) {
//            try {
//                log.info("------------进入发送邮件");
//                HashMap<String,String> data = examinationInfoMapper.sendResultToUser(inhabitantId);
//                String info = data.get("info");
//                JSONObject jsonObject = JSON.parseObject(info);
//                HashMap<String, String> resultMap = new HashMap<>();
//                if (jsonObject != null) {
//                    for (String key : jsonObject.keySet()) {
//                        resultMap.put(key, jsonObject.getString(key));
//                    }
//                }
//                byte[] bytes = PdfUtil.convertToPdf(resultMap);
//
//                MimeMessage mimeMessage = javaMailSender.createMimeMessage();
//                MimeMessageHelper mailMessage = new MimeMessageHelper(mimeMessage, true);
//
//                log.info("------------开始发送邮件");
//                mailMessage.setFrom(from);
//                mailMessage.setTo(data.get("email"));
//                mailMessage.setSubject("体检结果");
//                mailMessage.setText("您预约的用户："+data.get("name")+" 的体检结果结果见附件");
//                mailMessage.addAttachment(data.get("name")+"-体检单.pdf",new ByteArrayDataSource(bytes,"application/pdf"));
//
//                javaMailSender.send(mimeMessage);
//                log.info("------------发送邮件成功");
//            } catch (DocumentException e) {
//                throw new RuntimeException(e);
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            } catch (MessagingException e) {
//                throw new RuntimeException(e);
//            }
//        }
//
//        private void handlePendingList(){
//            while (true){
//                try {
//                    log.info("-----------开始处理pendingList");
//                    // 获取pending-list中的消息
//                    List<MapRecord<String,Object,Object>> list = redisTemplate.opsForStream().read(
//                            Consumer.from(GROUP_NAME, CONSUMER_NAME),
//                            StreamReadOptions.empty().count(1),
//                            StreamOffset.create(QUEUE_NAME, ReadOffset.from("0"))
//                    );
//                    log.info("-----------获取到pendingList消息：{}",list);
//                    if (list == null || list.isEmpty()){
//                        // 如果没有消息，则退出循环
//                        break;
//                    }
//                    log.info("-----------开始处理pendingList");
//                    // 获取消息体
//                    MapRecord<String, Object, Object> record = list.get(0);
//                    Map<Object, Object> value = record.getValue();
//                    // 发送邮件消息
//                    sendResultToUser(value.get("inhabitantId").toString());
//                    // ack消息确认
//                    redisTemplate.opsForStream().acknowledge(QUEUE_NAME,GROUP_NAME,record.getId());
//                }catch (Exception e){
//                    log.error("处理pendingList失败");
//                    try {
//                        Thread.sleep(200);
//                    }catch (InterruptedException ex){
//                        throw new RuntimeException();
//                    }
//                }
//            }
//        }
//
//
//
//    }
//
//
//
//
//}
//
